
const { getprodata, seacha, getprodatalx, getprobyid, getshopperdata } = require('../service/products')
const { getdata } = require('../service/shoper')

module.exports = {
    async getproducts(ctx, next) {
        const { address, offset, limit, shoperid } = ctx.request.body
        if (address) {
            const rudata = await getdata({ address, status: 1 })
            if (!rudata.length) {
                return ctx.body = {
                    code: 400,
                    msg: "附近没有商品"
                }
            }
            const shoperids = rudata.map(item => item.id)
            let productdata = await getprodata({ shoperid: shoperids, status: 1 }, offset, limit)
            let newdata = JSON.parse(JSON.stringify(productdata))
            // console.log(newdata)
            // for (let i = newdata.length - 1; i > 0; i--) {
            //     let random = Math.floor(Math.random() * i)
            //     // [newdata[i], newdata[random]] = [newdata[random], newdata[i]]
            //     let temp = newdata[i]
            //     newdata[i] = newdata[random]
            //     newdata[random] = temp
            // }
            return ctx.body = {
                code: 200,
                msg: "获取成功",
                data: newdata
            }
        }
        const rudata = await getprodata({ shoperid }, offset, limit)
        return ctx.body = {
            code: 200,
            msg: "获取成功",
            data: rudata
        }
    },
    async seachproducts(ctx, next) {
        const { seachdata, limit, offset } = ctx.request.body
        const shoperrudata = await getdata({ status: 1 })
        const shiperisd = shoperrudata.map(e => e.id)
        const producdata = await seacha(shiperisd, seachdata, limit, offset)
        return ctx.body = {
            code: 200,
            msg: "搜索成功",
            data: producdata
        }
    }
    ,
    async lxproducts(ctx, next) {
        const { lx, offset, limit, address } = ctx.request.body
        const rudata = await getdata({ address, status: 1 })
        const shoperids = rudata.map(item => item.id)
        const productdata = await getprodatalx(lx, offset, limit, shoperids)
        return ctx.body = {
            code: 200,
            msg: "获取成功",
            data: productdata
        }
    },
    async getbyid(ctx, next) {
        const { id } = ctx.request.body
        const productdata = await getprobyid({ id })
        const getdata = await getshopperdata(productdata.shoperid)
        return ctx.body = {
            code: 200,
            msg: "获取成功",
            productdata,
            getdata
        }
    }
}